/*
 * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wso2.carbon.registry.core.jdbc.handlers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.internal.RegistryCoreServiceComponent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Base class for edit processors of custom UIs. Handlers that generate edit or new resource UIs
 * should have an associated EditProcessor implementation. Custom UIs generated by UIEnabledHandlers
 * may have various input controls to get user input for filling up the resource content.
 * EditProcessor implementations should extract these inputs from the request and build the resource
 * content. Once the resource content is built, it should store the resource in the registry.
 */
public abstract class EditProcessor {

    private static final Log log = LogFactory.getLog(EditProcessor.class);

    /**
     * Implementations of this method should extract input parameters from edit view and update the
     * resource content.
     *
     * @param path        Path of the edited resource.
     * @param editViewKey UI key of the edit UI.
     * @param request     HttpServletRequest received from the the CustomUIServlet
     * @param response    HttpServletResponse to be sent the the CustomUIServlet
     *
     * @return true if response is sent within the EditProcessor implementation.
     * @throws RegistryException if an error occurs while processing content.
     */
    public abstract boolean processEditContent(
            String path,
            String editViewKey,
            HttpServletRequest request,
            HttpServletResponse response)
            throws RegistryException;

    /**
     * Implementations of this method should extract input parameters from new view and create a new
     * resource with that content.
     *
     * @param parentPath Path of the parent collection of new resource.
     * @param newViewKey UI key of the new UI.
     * @param request    HttpServletRequest received from the the CustomUIServlet
     * @param response   HttpServletResponse to be sent the the CustomUIServlet
     *
     * @return true if response is sent within the EditProcessor implementation.
     * @throws RegistryException if an error occurs while processing content.
     */
    public abstract boolean processNewContent(
            String parentPath,
            String newViewKey,
            HttpServletRequest request,
            HttpServletResponse response)
            throws RegistryException;

    /**
     * Obtains an instance of the Registry that the user can work with. If no user is logged in, the
     * Registry would be anonymous.
     *
     * @param request the HTTP Servlet Request.
     *
     * @return the Registry instance.
     * @throws RegistryException if an error occurs.
     */
    protected Registry getRegistry(HttpServletRequest request) throws RegistryException {

        Registry registry =
                (Registry) request.getSession().getAttribute(
                        RegistryConstants.ROOT_REGISTRY_INSTANCE);

        if (registry == null) {
            registry = RegistryCoreServiceComponent.getRegistryService().getRegistry();
        }

        return registry;
    }

    /**
     * Redirects the incoming request to the given URL.
     *
     * @param url      the target URL.
     * @param request  the HTTP Servlet Request.
     * @param response the HTTP Servlet Response.
     */
    @SuppressWarnings("unused")
    protected void redirect(String url, HttpServletRequest request, HttpServletResponse response) {

        request.setAttribute("redirect", "true");

        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            String msg = "Failed to redirect the response to the URL " + url +
                    ". Caused by: " + e.getMessage();
            log.error(msg, e);
        }
    }
}
